const recorderManager = wx.getRecorderManager();
var app = getApp();
import util from '../../../utils/util.js';
import commonAPI from '../../../api/api'
const FN = require('../../../utils/public');
const voice = wx.createInnerAudioContext();
const voice2 = wx.createInnerAudioContext();
var sto, correctSort = 1; 
Page({

  /**
   * 页面的初始数据 
   */
  data: {
    pritmplid:'',// 消息模板id【老师回复通知】
    currWordArr: [],
    currWordIndex: 0,
    hasrecording: false,
    cutdownTime: 60,
    bgcolor: 'FB5844',
    options: {},
    hasDeal: false,
    isPlaying: false,
    vrObj: {},
    priTmplIdArr: [],
    correctList: [],
    hasSub: false,
    hasIntegralBtn: false,// 是否免积分纠音
  },

  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    wx.hideShareMenu(); // 禁止分享
    this.setData({
      options: options
    })
    if (options.freeCorrectMode=='true') {
      this.setData({
        hasIntegralBtn: true,// 免积分
      })
    }else{
      // 不免积分
      this.setData({
        hasIntegralBtn: false,// 不免积分        
      })
    }
    this.initData();
    this.getSubscribeMsg();
  },

  initData: function () {
    var that = this;
    commonAPI.getvrandteaInfo({ voiceResultId: that.data.options.vrId }).then(res => {
      if (res.code == '200') {
       if (res.data.hasDeal) {
          FN.Toast('预约已处理')
        }
          var vr = res.data.vrInfo[0];
          vr.voiceResultInfo = JSON.parse(vr.voiceResultInfo);
          var temarr = [], wordsArr = [];
          if (vr.voiceResultAIModel=='1'){
            if (vr.voiceResultInfo.result.words.length == 0) {
              var arr = temarr = vr.voiceToen.split(' ');
              for (var i = 0; i < arr.length; i++) {
                var o = { word: arr[i], pron_accuracy: 0 }
                wordsArr.push(o);
              }
              vr.hasRepeatWord = 0;
              vr.voiceResultInfo.result.words = wordsArr;
              vr.hasRepeatWord = 0;
            } else {
              vr.voiceResultInfo.result.words.map(function (item, i, arr) {
                temarr.push(item.word);
              });
            }
          }else{
            if (vr.voiceResultInfo.Words.length == 0) {
              var arr = temarr = vr.voiceToen.split(' ');
              for (var i = 0; i < arr.length; i++) {
                var o = { word: arr[i], PronAccuracy: 0 }
                wordsArr.push(o);
              }
              vr.hasRepeatWord = 0;
              vr.voiceResultInfo.Words = wordsArr;
              vr.hasRepeatWord = 0;
            } else {
              vr.voiceResultInfo.Words.map(function (item, i, arr) {
                temarr.push(item.Word);
              });
            }
          }          
          vr.voiceResultAccuracy = isNaN(vr.voiceResultAccuracy) == true ? 0 : vr.voiceResultAccuracy;
          temarr.unshift("整句");
          temarr.unshift("语调");
          temarr.unshift("连读");
          temarr.unshift("发音技巧");
          that.setData({
            currWordArr: temarr
          })
          that.setData({
            vrObj: vr
          })
        that.setData({
          hasDeal: res.data.hasDeal,
          pritmplid:res.data.pritmplIdObj.priTmplId
        })
      }
    })
  },

  // 播放原音 originalvoiceurl
  playOriginalVoice: function () {
    if (this.data.vrObj.voiceFileType == '2') {
      this.playSMvoiceFile(this.data.vrObj);// 播放小音频
    } else {
      this.playVoiceByTimes(this.data.vrObj);// 播放时间段模式
    }
  },

  // 小段音频播放
  playSMvoiceFile(obj){
    voice.stop();
    voice.src = obj.voiceSystemURL;
    voice.play();
    voice.onPlay(function () {
      wx.showLoading({
        title: '原音播放中···',
      })
    });

    voice.onStop(function () {
      wx.hideLoading();
    });

    // 音频结束回调
    voice.onEnded(function () {
      wx.hideLoading();
    });
  },

  // 播放音频按照时间段，新方法
  playVoiceByTimes(obj) {
    wx.showLoading({
      title: '原音播放中···',
    })
    var that = this;
    const bam = wx.getBackgroundAudioManager();
    const star = parseFloat(obj.timing);
    const end = parseFloat(obj.endTiming);
    bam.src = obj.voiceSystemURL
    bam.title = obj.voiceToen
    bam.epname = obj.voiceToen// 专辑名，原生音频播放器中的分享功能，分享出去的卡片简介，也将使用该值
    bam.singer = obj.voiceToen
    bam.coverImgUrl = obj.voiceSystemImage
    bam.startTime = star;
    bam.play();
    bam.onPlay(function () {
      setTimeout(() => {
        bam.stop()
      }, (end - star) * 1000);
    })
    bam.onError(function () {
      bam.stop()
      wx.hideLoading();
    })

    // 暂停
    bam.onStop(function () {
      wx.hideLoading();
    })

    // 播放结束
    bam.onEnded(() => {
      bam.stop()
      var btnObjState = "btnimgarr[0]";
      that.setData({
        [btnObjState]: 1
      })
    })
  },

  // 播放声音
  playVoice: function (e) {
    var voiceurl = e.currentTarget.dataset.voiceurl;
    voice.stop();
    voice.src = voiceurl;
    voice.play();
    voice.onPlay(function () {
      wx.showLoading({
        title: '播放中···',
      })
    });

    voice.onStop(function () {
      wx.hideLoading();
    });

    // 音频结束回调
    voice.onEnded(function () {
      wx.hideLoading();
    });
  },

  // 删除
  delCorrectVoice: function (e) {
    var i = e.currentTarget.dataset.index, that = this;
    that.data.correctList.splice(i, 1);
    that.setData({
      correctList: that.data.correctList
    })
  },

  // 询问是否提交
  subdata: function () {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否提交',
      success(res) {
        if (res.confirm) {
          if(!that.data.pritmplid){
            FN.Toast('消息模板id不允许为空')
          }else if (!that.data.hasSub) {
            that.saveCorrect();
          } else {
            FN.Toast('已提交,请勿重复提交')
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 保存数据
  saveCorrect: function () {
    var that = this;
    if (that.data.correctList.length == 0) {
      FN.Toast('请先选择单词，并且上传录音')
      return;
    }
    commonAPI.teapushmsg({
      correctListJson: JSON.stringify(that.data.correctList),
      vsId: that.data.vrObj.voiceSystemId,
      voiceResultId: that.data.vrObj.voiceResultId,
      wdTeacherId: app.globalData.userInfo.userObj.wdTeacherId,// 老师id
      teacherName: app.globalData.userInfo.userObj.wdTeacherName,// 老师姓名
      receiverOpenId: that.data.vrObj.openId,
      pritmplid:that.data.pritmplid,
      voiceToen: that.data.vrObj.voiceToen,
      baid: that.data.vrObj.beforehandAppointmentId,
      hasConsumeIntegral: that.data.hasIntegral?'-1':0,
      "wxOpenInfoSource": that.data.vrObj.wxOpenInfoSource
    }).then(res => {
      if (res.code == '200') {
        if (res.data == "0") {
          FN.Toast('纠音成功，消息已送达')
        } else {
          if (res.data == "0") {
            FN.Toast('纠音成功，但消息未送到,原因：' + res.msg)
          }
        }
        that.setData({
          hasDeal: true
        })
        setTimeout(() => {
          wx.navigateTo({
            url: '../one2oneCorrect/one2oneCorrect?wdTeacherName=' + app.globalData.userInfo.userObj.wdTeacherName + '&wdTeacherId=' + app.globalData.userInfo.userObj.wdTeacherId
          })
        }, 500);
      }
    })
  },

  bindPicker3Change: function (e) {
    this.setData({
      currWordIndex: e.detail.value
    })
  },

  // 试听老师的发音
  listenVoice: function (e) {
    var voiceurl = e.currentTarget.dataset.correctvoiceurl;
    voice2.stop();
    voice2.src = voiceurl;
    voice2.play();
    voice2.onPlay(function () {
      wx.showLoading({
        title: '播放中···',
      })
    });

    voice2.onStop(function () {
      wx.hideLoading();
    });

    // 音频结束回调
    voice2.onEnded(function () {
      wx.hideLoading();
    });
  },

  // 倒计时
  cutdownTime: function () {
    var time = 59, that = this;
    sto = setInterval(function () {
      if (time < 0) {
        clearInterval(sto);
        that.stopRecording();
      } else {
        that.setData({
          cutdownTime: time--
        })
      }
    }, 1000)
  },

  // 红点闪烁
  redRight: function () {
    var that = this;
    var sto = setInterval(function () {
      if (that.data.bgcolor == 'ffffff') {
        that.setData({
          bgcolor: 'FB5844'
        })
      } else {
        that.setData({
          bgcolor: 'ffffff'
        })
      }
    }, 800)
  },

  // 开始录音
  recording: function () {
    var that = this;
    const options = {
      duration: 60000,//指定录音的时长，单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式，有效值 aac/mp3
      frameSize: 50,//指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      wx.showLoading({
        title: '录音中···'
      })
      console.log('recorder start')
      that.setData({
        hasrecording: true
      })
      that.cutdownTime();
      that.redRight();
    });
    //错误回调
    recorderManager.onError((res) => {
      // that.stopRecording();
    })
  },

  // 暂停录音
  stopRecording: function () {
    var that = this;
    wx.hideLoading();
    recorderManager.stop();
    this.setData({
      hasrecording: false
    })
    clearInterval(sto);
    recorderManager.onStop((res) => {
      console.log('停止录音', res.tempFilePath);
      this.setData({
        hasrecording: false
      })
      clearInterval(sto);
      that.subVoiceInfo(res);
    })
  },

  // 上传到七牛云服务器
  subVoiceInfo: function (teacherCorrect) {
    var that = this, filePath = teacherCorrect.tempFilePath, fileName = "Teacher's_pronunciation_correction_" + new Date().getTime() + ".mp3";

    util.initQiniu();
    // 向七牛云上传
    util.qiniuUploaderUpload(filePath, fileName, (res) => {
      var obj = {},
        tmparr = [];
      obj.word = that.data.currWordArr[that.data.currWordIndex];
      obj.correctVoiceUrl = res.fileURL;
      obj.voiceSystemId = that.data.vrObj.voiceSystemId;
      obj.avatarurl = app.globalData.userInfo.userObj.avatarUrl// 老师头像，用于在audio自定义组件显示老师头像。
      obj.wdTeacherName = app.globalData.userInfo.userObj.wdTeacherName// 老师头像，用于在audio自定义组件显示老师头像。
      obj.correctType = 3;
      obj.correctSort = ++correctSort;
      tmparr = that.data.correctList;
      tmparr.push(obj);
      that.setData({
        correctList: tmparr
      })
    })
  },

  audioClick: function (e) {
    var url = e.currentTarget.dataset.url;
    var obj = { useWebAudioImplement: false };
    var iac = wx.createInnerAudioContext(obj);
    iac.src = url;
    iac.onPlay(function () {
      wx.showLoading({
        mask: false,
        title: '播放中···'
      })
    })
    iac.onEnded(function () {
      wx.hideLoading();
    })
    this.setData({
      isPlaying: !this.data.isPlaying
    })
    if (this.data.isPlaying) {
      iac.play();
    } else {
      iac.pause();
    }
  },
  // 获取订阅消息
  getSubscribeMsg: function () {
    var that = this;
    commonAPI.getSubscribeMsg({ pageUrl: util.getCurrentPageUrl() }).then(res => {
      if (res.code == '200' && res.data.length > 0) {
        var arr = res.data[0].priTmplIdArr.split(",")
        that.setData({
          priTmplIdArr: arr
        })
      }
    })
  },

  // 是否需要消耗积分选项事件
  hasIntegralStatus: function (e) {
    this.setData({
      hasIntegral: e.detail.value
    })
  },
})

